package com.example.kits;

import android.app.ProgressDialog;
import android.content.Context;
import android.widget.Toast;

import java.util.concurrent.atomic.AtomicInteger;

public class Tip {


    public static void toast(Context ctx, String msg) {
        Main.run(() -> Toast.makeText(ctx, msg, Toast.LENGTH_LONG).show());
    }

    private static ProgressDialog loading = null;
    private static AtomicInteger loadings = new AtomicInteger(0);

    // 显示加载框
    public static void showLoading(Context ctx) {
        showLoading(ctx, "正在加载，请稍等...");
    }

    // 显示加载框
    public static void showLoading(Context ctx, String msg) {
        if (ctx == null) {
            throw new IllegalArgumentException("ctx can not be null");
        }
        Main.run(() -> {
            synchronized (Main.class) {
                if (loading == null) {
                    loading = new ProgressDialog(ctx);
                }
            }
            loading.setMessage(msg);
            loadings.incrementAndGet();
            loading.show();
        });
    }

    // 关闭加载框
    public static void hideLoading() {
        Main.run(() -> {
            // 判断是否所有显示加载框的接口都已完成
            if (loadings.decrementAndGet() <= 0
                    && loading != null) {
                loading.dismiss();
                loading = null;
            }
        });
    }


}
